#include "career.h"

/* "Choose next city" screen */

// Dependency on libsmacker
#include <Smacker/smacker.h>

// Send in the externs
extern GLuint cursor_list;
extern struct cfg_struct *cfg;
extern GLfloat aspect;
extern int mx, my;

extern char career_movie[256];

static Uint32 career_next_frame(Uint32 interval, void *param)
{
    SDL_Event event;
    SDL_UserEvent userevent;

    /* In this example, our callback pushes an SDL_USEREVENT event
	 into the queue, and causes ourself to be called again at the
	 same interval: */

    userevent.type = SDL_USEREVENT;
    userevent.code = 0;
    userevent.data1 = NULL;
    userevent.data2 = NULL;

    event.type = SDL_USEREVENT;
    event.user = userevent;

    SDL_PushEvent(&event);
    return(interval);
}

int career_main(int level)
{
    // set to 0 to run.  set to non-zero to exit and change gamestate
	int done = 0,i;

    // Videos
    smk s[3];
	SDL_TimerID frame_timer;

	// Integer which holds the current frame texture
	SDL_Surface *frame = NULL;
    GLuint frame_tex[3];
	// Other UI textures
	GLuint career_tex[2];
	// Screen positioning (letterbox / pillarbox)
	GLuint xoffset, yoffset;

	float scale_x, scale_y, unscale_x, unscale_y;

	char filename[256];

    for (i = 0; i < 3; i++)
    {
        sprintf(filename,"data/video/city%d_s.smk", (level * 3) + i);

        if (!(s[i] = smk_open(filename,SMK_MODE_MEMORY)))
        {
            /* Unable to load SMK file. Rats. */
            printf("WARNING: Unable to load %s\n",filename);
//            return GAMESTATE_;
        }

        smk_enable_palette(s[i],1);
        smk_enable_video(s[i],1);

        smk_first(s[i]);

        frame = tex_from_smkframe(smk_get_palette(s[i]),smk_get_video(s[i]),smk_info_video_w(s[i]),smk_info_video_h(s[i]));
        if (frame == NULL)
        {
            fprintf(stderr,"WARNING: tex_from_smkframe returned NULL.\n");
//            done = GAMESTATE_ERROR;
        } else {
            frame_tex[i] = build_texture (frame, GL_LINEAR);
            SDL_FreeSurface(frame);
        }
    }

	career_tex[0] = load_texture("career",GL_LINEAR);
	career_tex[1] = load_texture("carsel",GL_LINEAR);

	/* Perform a conversion for scaled items to screen coords. */
    float movie_aspect = (614.0f / 435.0f);
    if (movie_aspect > aspect) // 16:9 movie on narrow screen: match W, scale H
    {
		scale_x = 614.0f;
		scale_y = 614.0f / aspect;
		xoffset = 0;
		yoffset = (((614.0f / aspect) - 435.0f) / 2) + .5;
    }
    else // 4:3 movie on wider screen: match H, scale W
    {
		scale_x = aspect * 435.0f;
		scale_y = 435.0f;
		xoffset = (((435.0f * aspect) - 614.0f) / 2) + .5;
		yoffset = 0;
    }
	unscale_x = (float)cfg_get_int(cfg,"SCREEN_X");
	unscale_y = (float)cfg_get_int(cfg,"SCREEN_Y");

	GLuint quad_list = glGenLists(1);
	glNewList(quad_list, GL_COMPILE);
		glBox(xoffset,yoffset,614.0f,435.0f,career_tex[0]);
	glEndList();

    /* draws the three video boxes */
    GLuint city_list = glGenLists(3);
	glNewList(city_list, GL_COMPILE);
		glBox(xoffset + 77,yoffset + 70, 200, 108, frame_tex[0]);
    glEndList();
	glNewList(city_list + 1, GL_COMPILE);
		glBox(xoffset + 339,yoffset + 70, 200, 108, frame_tex[1]);
    glEndList();
	glNewList(city_list + 2, GL_COMPILE);
		glBox(xoffset + 77,yoffset + 248, 200, 108, frame_tex[2]);
    glEndList();

	/* Load MUSIC */
	Mix_Music *career_music = load_music("career");
	if(!career_music) {
		printf("music_load(\"careerback\"): %s\n", Mix_GetError());
	} else {
		if(Mix_PlayMusic(career_music, -1)==-1) {
			printf("Mix_PlayMusic: %s\n", Mix_GetError());
		}
	}

	Mix_Chunk *career_click = load_wave("menu");
	if(!career_click) {
		printf("music_load(\"careerclick\"): %s\n", Mix_GetError());
	}

	unsigned char highlighted = 0;

	// Start the video timer
	frame_timer = SDL_AddTimer((Uint32)((1000.0f / smk_info_fps(s[0])) + 0.5f), career_next_frame, NULL);

	SDL_GetMouseState(&mx, &my);

	SDL_Event event;

	unsigned char dirty = 1;
	int trans_x, trans_y;

	while (!done)
	{
		/* Check for events */
        /* Keypress skips to video 2 */
		while (SDL_PollEvent (&event))
		{
			switch (event.type)
			{
				case SDL_USEREVENT:
					dirty = 1;
					for (i = 0; i < 3; i ++)
					{
                        if (smk_next(s[i]) == SMK_DONE)
                        {
                            // movie over, out of frames
                            smk_first(s[i]);
                        }

                        frame = tex_from_smkframe(smk_get_palette(s[i]),smk_get_video(s[i]),smk_info_video_w(s[i]),smk_info_video_h(s[i]));
                        if (frame == NULL)
                        {
                            fprintf(stderr,"WARNING: tex_from_smkframe returned NULL.\n");
                            done = GAMESTATE_ERROR;
                        } else {
                            glBindTexture(GL_TEXTURE_2D,frame_tex[i]);
                            rebuild_texture (frame_tex[i], frame);
                            SDL_FreeSurface(frame);
                        }
					}
					break;
				case SDL_KEYUP:
					if (event.key.keysym.sym == SDLK_ESCAPE)
						done = GAMESTATE_MENU;
					//                    done = next_gamestate;
					break;
				case SDL_MOUSEMOTION:
					// mouse move = cursor redraw
					dirty = 1;

					mx = event.motion.x;
					my = event.motion.y;

					// convert x / y to scale-coords
					trans_x = (event.motion.x * scale_x / unscale_x) - xoffset;
					trans_y = (event.motion.y * scale_y / unscale_y) - yoffset;

					if (trans_x > 77 && trans_x < 277)
					{
						if (trans_y > 70 && trans_y < 178)
						{
							i = 0;
						}
						else if (trans_y > 248 && trans_y < 356)
						{
							i = 2;
						}
					} else if (trans_x > 339 && trans_x < 539 && trans_y > 90 && trans_y < 178) {
					    i = 1;
					} else {
					    i = 3;
					}

                    /* Design change: original game always had something highlighted.
                         Now, you must be in the box.  Outside that puts you in highlight 5, which means
                         you go to Credits on click instead. */
					if (i != highlighted)
					{
					    Mix_PlayChannel(-1,career_click,0);
					    highlighted = i;
					}

					break;
				case SDL_MOUSEBUTTONUP:
					if (highlighted < 3)
					{
					    sprintf(career_movie, "city%d_b",(level * 3) + highlighted);
					    fprintf(stderr,"%s\n",career_movie);
					    done = GAMESTATE_CAREER_MOVIE;
					}
					break;
				case SDL_QUIT:
                    done = GAMESTATE_EXIT;
					break;
				default:
					break;
			}
		}

		if (dirty) {
			/* Nuke everything */
			glClear(GL_COLOR_BUFFER_BIT);

			/* Put us into GLOrtho mode */
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			/* Match movie resolution */
			/* This is to draw "scaled" UI elements */
			glOrtho(0.0f,scale_x,scale_y,0.0f,-1.0f,1.0f);

			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glCallList(quad_list);

// Highlights
            if (highlighted < 3)
            {
                glBindTexture(GL_TEXTURE_2D, career_tex[1]);
				if (highlighted == 0)
				{
					glBegin(GL_QUADS);
						glTexCoord2f(0,0);
						glVertex2i(xoffset, yoffset);
						glTexCoord2f(0,.5);
						glVertex2i(xoffset, yoffset + 350);
						glTexCoord2f(.5,.5);
						glVertex2i(xoffset + 275, yoffset + 350);
						glTexCoord2f(.5,0);
						glVertex2i(xoffset + 275, yoffset + 0);
					glEnd();
				} else if (highlighted == 1) {
					glBegin(GL_QUADS);
						glTexCoord2f(0.5,0);
						glVertex2i(xoffset + 200, yoffset);
						glTexCoord2f(0.5,.5);
						glVertex2i(xoffset + 200, yoffset + 350);
						glTexCoord2f(1,.5);
						glVertex2i(xoffset + 475, yoffset + 350);
						glTexCoord2f(1,0);
						glVertex2i(xoffset + 475, yoffset + 0);
					glEnd();
				} else {
					glBegin(GL_QUADS);
						glTexCoord2f(0,0.5);
						glVertex2i(xoffset, yoffset + 200);
						glTexCoord2f(0,1);
						glVertex2i(xoffset, yoffset + 550);
						glTexCoord2f(.5,1);
						glVertex2i(xoffset + 275, yoffset + 550);
						glTexCoord2f(.5,0.5);
						glVertex2i(xoffset + 275, yoffset + 200);
					glEnd();
				}
            }

			glCallList(city_list);
			glCallList(city_list + 1);
			glCallList(city_list + 2);

			/* Flip back into GLOrtho mode */
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			/* Match screen resolution */
			/* This is to draw "unscaled" UI elements */
			glOrtho(0.0f,unscale_x,unscale_y,0.0f,-1.0f,1.0f);

			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glEnable(GL_ALPHA_TEST);
			glPushMatrix();
				glTranslatef(mx,my,0);
				glCallList(cursor_list);
			glPopMatrix();
			glDisable(GL_ALPHA_TEST);

			SDL_GL_SwapBuffers();

			dirty = 0;
		}

		/* Don't run too fast */
		SDL_Delay (1);
	}

	/* shutdown frame timer */
	SDL_RemoveTimer(frame_timer);

	/* end music */
	if (career_click != NULL) { Mix_FreeChunk(career_click); }
	if (career_music != NULL) { Mix_HaltMusic(); Mix_FreeMusic(career_music); }

    glDeleteLists(city_list, 3);
    glDeleteLists(quad_list, 1);

	glDeleteTextures( 2, career_tex);
	glDeleteTextures( 3, frame_tex );

	smk_close(s[0]);
	smk_close(s[1]);
	smk_close(s[2]);

	return done;
}

